package core;

public class Senses {

	private static final class Holder extends ThreadLocal<Senses> {
		@Override
		protected Senses initialValue() {
			return new Senses();
		}
	}

	private static final Holder holder = new Holder();
	
	private float[] proximity = new float[8], light = new float[8], velocity = new float[2];
	private float energy = 0, compass = 0, ground = 0;

	private static synchronized void assignSensors(String cmd, String resp, float[] sensors, int norm){
		String[] sensorStrings = Bridge.request(cmd).split(",");
		if(sensorStrings[0].compareTo(resp) == 0){
			for(int index = 1; index < sensorStrings.length; index++){
				sensors[index-1] = Float.parseFloat(sensorStrings[index]) / norm;
			}
		}else{
			System.err.println("Error reading sensors: "+cmd);
			for (int i = 0; i < sensors.length; i++) {
				sensors[i] = 0;
			}
		}
	}
	
	private static synchronized float getSensors(String cmd, String resp){
		String[] sensorStrings = Bridge.request(cmd).split(",");
		if(sensorStrings[0].compareTo(resp) == 0){
			return Float.parseFloat(sensorStrings[1]);
		}else{
			System.err.println("Error reading sensors: "+cmd);
			return 0;
		}
	}
	
	public static void readProximity() {
		assignSensors("N", "n", holder.get().proximity, 1);
	}

	public static synchronized float getProximity(int index) {
		return holder.get().proximity[index];
	}
	
	public static void readLight() {
		assignSensors("O", "o", holder.get().light, 1024);
	}
	
	public static synchronized float getLight(int index) {
		return holder.get().light[index];
	}
	
	public static void readVelocity(){
		assignSensors("E","e",holder.get().velocity,1);
	}
	
	public static synchronized float getVelocity(int index) {
		return holder.get().velocity[index];
	}
	
	public static synchronized void readEnergy(){
		holder.get().energy = getSensors("#E", "#e");
	}
	
	public static synchronized float getEnergy(){
		return holder.get().energy;
	}
	
	public static synchronized float readCompass(){
		holder.get().compass = getSensors("#C", "#c");
		return getCompass();
	}
	
	public static synchronized float getCompass(){
		return holder.get().compass;
	}
	
	public static synchronized void readGround(){
		holder.get().ground = getSensors("#G", "#g");
	}
	
	public static synchronized boolean isOnGround(){
		return holder.get().ground == 1;
	}

}
